﻿/*
PXP2 : Polygeek Xml Parsing Project
version: 1.0
Date: 2007.02.06

Dan Florio
polyGeek.com
oz@polyGeek.com

Visit: http://polyGeek.com/PXP2/ for help.

*/

class com.polygeek.utils.PXP2 {
	public function PXP2(xmlPath:String, xmlParsed_CB:Function, isTimed:Boolean) {
		var xml2load:XML = new XML();
		
		if( xmlPath.substr(xmlPath.length - 4, xmlPath.length) == ".xml" ) {
			xml2load.onLoad = function(success:Boolean):Void {
				if(success) {
					var obj:Object = new Object();
					if( isTimed ) {
						var beforeTime:Number = new Date().valueOf();
					}
					obj = toObject(this);
					if( isTimed ) {
						var afterTime:Number = new Date().valueOf();
						trace("It took " + Number( afterTime - beforeTime ) + " milliseconds to parse.");
					}
					xmlParsed_CB(obj[this.firstChild.nodeName]);
					this = undefined;
				} else {
					trace("*** XML Loading Error: XML file not found or connection failed ***");
				}
			};
			xml2load.ignoreWhite = true;
			xml2load.load(xmlPath);
		} else {
			xml2load.parseXML(xmlPath);
			var obj:Object = new Object();
			obj = toObject(xml2load);
			xmlParsed_CB(obj[xml2load.firstChild.nodeName]);
			xml2load = undefined;
		}
	} // end constructor


	public static function toObject(xml:Object):Object {
		var parse:Function = function (n) {
			var o:Object = new String (n.firstChild.nodeValue);
			var s:Object = new Object();
			var t:Object = new Object();

			for (s = (o == "null") ? n.firstChild : n.childNodes[0]; s != null; s = s.nextSibling) {
				t = ( s.childNodes.length ) ? parse(s) : new String (s.nodeValue);
				
				for (var a:String in s.attributes) {
					if(s.attributes[a] == "false") {
						t[a] = false;
					} else if(s.attributes[a] == "true") {
						t[a] = true;
					} else if(!isNaN(s.attributes[a])) {
						t[a] = Number(s.attributes[a]);			
					} else {
						t[a] = String(s.attributes[a]);
					}
				}
				if ( o[s.nodeName] != undefined ) {
					if( !(o[s.nodeName] instanceof Array) ) {
						o[s.nodeName] = [o[s.nodeName]];
					}
					o[s.nodeName].push(t);
				} else if( s.nodeName != null ) {
					o[s.nodeName] = t;
				}
			}
		return o;
		};
	return parse (xml);
	}
} // end of class